package com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.ydkj.a37e_mall.Classes.Model.Response.GetShopListResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.StatusBarUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

/**
 * Created by Administrator on 2017/2/13..
 * 门店详细
 */

public class StoreDetail extends BaseActivity implements View.OnClickListener {
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private LinearLayout lly_main;
    private ImageView img_back;
    private WebView wv_store;
    private LinearLayout lly_phone, lly_gps, lly_share;
    ProgressDialog progDlg = null;

    private List<GetShopListResp.ResultEntity.DataEntity> shopDataEntityList;
    private String tel, jingdu, weidu, share_url, detail_url;

    private PopupWindow pop_phone;
    private LinearLayout lly_pop_phone;
    private TextView tv_pop_phone, tv_pop_cancel;

    private int page;
    public static final String TAG = "NaviSDkDemo";
    private static final String APP_FOLDER_NAME = "BNSDKDemo";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private Button mGcjNaviBtn = null;
    private String mSDCardPath = null;
    private String authinfo = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.store_detail);

        mActivity = this;
        init();
        ShareSDK.initSDK(mActivity);
        BNOuterLogUtil.setLogSwitcher(true);//
        if (initDirs()) {
            Log.e("ssss", "initNavi");
            initNavi();
        }
//        initWindow();
    }

    private void initWindow() {
        StatusBarUtil.setColor(mActivity, getResources().getColor(R.color.A000000), 0);
    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        progDlg = new ProgressDialog(mActivity);
        shopDataEntityList = new ArrayList<GetShopListResp.ResultEntity.DataEntity>();

        if (this.getIntent().getExtras() != null) {
            shopDataEntityList = (ArrayList<GetShopListResp.ResultEntity.DataEntity>) this.getIntent().getExtras().getSerializable("shopDataEntityList");

            Log.e("url", "tel==" + shopDataEntityList.get(0).getTel());
            Log.e("url", "jingdu==" + shopDataEntityList.get(0).getLng());
            Log.e("url", "weidu==" + shopDataEntityList.get(0).getLat());
//            Log.e("url", "detail_url==" + shopDataEntityList.get(0).getDetail_url());
//            Log.e("url", "share_url==" + shopDataEntityList.get(0).getShare_url());
        }
        lly_main = (LinearLayout) mActivity.findViewById(R.id.lly_main);
        img_back = (ImageView) mActivity.findViewById(R.id.img_back);
        lly_phone = (LinearLayout) mActivity.findViewById(R.id.lly_phone);
        lly_gps = (LinearLayout) mActivity.findViewById(R.id.lly_gps);
        lly_share = (LinearLayout) mActivity.findViewById(R.id.lly_share);
        wv_store = (WebView) mActivity.findViewById(R.id.wv_store);

        initWebView();
        initPhonePopupWindow();

        img_back.setOnClickListener(this);
        lly_phone.setOnClickListener(this);
        lly_gps.setOnClickListener(this);
        lly_share.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back://返回
                finish();
                break;
            case R.id.lly_phone://电话
                pop_phone.setAnimationStyle(R.style.popupWindowAnimation);
                pop_phone.showAtLocation(mActivity.findViewById(R.id.lly_main), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                pop_phone.update();
                break;
            case R.id.lly_gps://导航
                Log.e("url", "111");
                if (BaiduNaviManager.isNaviInited()) {
                    Toast.makeText(mActivity, "百度导航即将开始", Toast.LENGTH_SHORT).show();
                    routeplanToNavi(Double.parseDouble(shopDataEntityList.get(0).getLat()), Double.parseDouble(shopDataEntityList.get(0).getLng()), BNRoutePlanNode.CoordinateType.GCJ02);

//                        routeplanToNavi(116.377248, 40.01337, BNRoutePlanNode.CoordinateType.GCJ02);

                }
                break;
            case R.id.lly_share://分享
//                showShare(shopDataEntityList.get(0).getShare_url(), shopDataEntityList.get(0).getName());
                showShare("http://sharesdk.cn", shopDataEntityList.get(0).getName());

                break;
        }

    }


    private void initPhonePopupWindow() {
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        View layout = inflater.inflate(R.layout.pop_phone, null);
        lly_pop_phone = (LinearLayout) layout.findViewById(R.id.lly_pop_phone);
        tv_pop_phone = (TextView) layout.findViewById(R.id.tv_pop_phone);
        tv_pop_cancel = (TextView) layout.findViewById(R.id.tv_pop_cancel);

        tv_pop_phone.setText(shopDataEntityList.get(0).getTel());

        layout.invalidate();
        pop_phone = new PopupWindow(layout, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pop_phone.setBackgroundDrawable(new BitmapDrawable());
        pop_phone.setOutsideTouchable(true);
        pop_phone.setFocusable(true);

        lly_pop_phone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri data = Uri.parse("tel:" + tv_pop_phone.getText().toString());
                intent.setData(data);
                startActivity(intent);
                pop_phone.dismiss();
                pop_phone.setFocusable(false);
            }
        });

        tv_pop_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop_phone.dismiss();
                pop_phone.setFocusable(false);
            }
        });

    }

    //分享
    private void showShare(String url, String text) {
        ShareSDK.initSDK(mActivity);

        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
        // titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText(text);
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);

        // 启动分享GUI
        oks.show(mActivity);
    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        wv_store.addJavascriptInterface(new JavascriptInterface(mActivity), "android");
        wv_store.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        // 设置WebView属性，能够执行Javascript脚本
        wv_store.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        wv_store.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        wv_store.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        wv_store.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        wv_store.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wv_store.getSettings().setLoadWithOverviewMode(true);
        // 加载需要显示的网页
//        wv_store.loadUrl(shopDataEntityList.get(0).getDetail_url());
        // 设置Web视图
        wv_store.setWebViewClient(new MyWebViewClient());
    }

    public class JavascriptInterface {
        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }

    }

    // 监听 所有点击的链接，如果拦截到我们需要的，就跳转到相对应的页面。
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.contains("id:")) {
//                Intent intent = new Intent(ActivityWebView.this, EnrollTryToPlay.class);
//                intent.putExtra("url", url);
//                Log.e("url", "url==" + url);
//                ActivityWebView.this.startActivity(intent);
//                finish();
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (progDlg == null || !progDlg.isShowing()) {
                progDlg.setMessage("正在加载，请稍候...");
            }
            progDlg.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
            progDlg.dismiss();
        }
    }

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        BaiduNaviManager.getInstance().init(mActivity, mSDCardPath, APP_FOLDER_NAME,
                new BaiduNaviManager.NaviInitListener() {
                    @Override
                    public void onAuthResult(int status, final String msg) {
                        if (0 == status) {
                            authinfo = "key校验成功!";
                            Log.e("ssss", "key校验成功");
                        } else {
                            authinfo = "key校验失败, " + msg;
                            Log.e("ssss", "key校验失败");
                        }
                        mActivity.runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
//                                Toast.makeText(mActivity, authinfo, Toast.LENGTH_LONG).show();
                                Log.e("ssss", "Map_authinfo==" + authinfo);
                            }
                        });

                    }

                    public void initSuccess() {
//                        Toast.makeText(mActivity, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                        Log.e("ssss", "Map_百度导航引擎初始化成功");
                    }

                    public void initStart() {
//                        Toast.makeText(mActivity, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
                        Log.e("ssss", "Map_百度导航引擎初始化开始");
                    }

                    public void initFailed() {
//                        Toast.makeText(mActivity, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
                        Log.e("ssss", "Map_百度导航引擎初始化失败");
                    }
                }, null /*mTTSCallback*/);
    }

    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    public void routeplanToNavi(double jingdu, double weidu, BNRoutePlanNode.CoordinateType coType) {
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        Log.e("url", "目的地址:经度==" + jingdu + " 纬度==" + weidu);

        switch (coType) {
            case GCJ02: {
                Log.e("ssss", "导航");
                sNode = new BNRoutePlanNode(Double.parseDouble(sharedPreferencesUtil.getJingdu()), Double.parseDouble(sharedPreferencesUtil.getWeidu()), "目前地址", null, coType);

                eNode = new BNRoutePlanNode(jingdu, weidu, "目的地", null, coType);
                Log.e("url", "sNode==" + sNode + "   eNode==" + eNode);
                Log.e("url", "当前地址:纬度==" + sharedPreferencesUtil.getJingdu() + " 经度==" + sharedPreferencesUtil.getWeidu());
                Log.e("url", "目的地址:经度==" + jingdu + " 纬度==" + weidu);
                break;
            }
//            case WGS84: {
//                sNode = new BNRoutePlanNode(116.300821, 40.050969,
//                        "百度大厦", null, coType);
//                eNode = new BNRoutePlanNode(116.397491, 39.908749,
//                        "北京天安门", null, coType);
//                break;
//            }
//            case BD09_MC: {
//                sNode = new BNRoutePlanNode(12947471, 4846474,
//                        "百度大厦", null, coType);
//                eNode = new BNRoutePlanNode(12958160, 4825947,
//                        "北京天安门", null, coType);
//                break;
//            }
            default:

        }
        if (sNode != null && eNode != null) {
            List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(sNode);
            list.add(eNode);
            BaiduNaviManager.getInstance().launchNavigator(mActivity, list, 1, true, new DemoRoutePlanListener(sNode));
        }
    }

    public class DemoRoutePlanListener implements BaiduNaviManager.RoutePlanListener {

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public DemoRoutePlanListener(BNRoutePlanNode node) {
            Log.e("url", "DemoRoutePlanListener");
            mBNRoutePlanNode = node;
            Log.e("url", "mBNRoutePlanNode==" + mBNRoutePlanNode);
        }

        @Override
        public void onJumpToNavigator() {
            Log.e("url", "onJumpToNavigator_BNDemoGuideActivity");
            Intent intent = new Intent(mActivity, BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            startActivity(intent);
        }

        @Override
        public void onRoutePlanFailed() {
            // TODO Auto-generated method stub
            Log.e("url", "onRoutePlanFailed");
        }

    }


    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(
                Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ShareSDK.stopSDK(mActivity);
    }
}
